package cn.vote.web.servlet;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;



import cn.itcast.servlet.BaseServlet;
import cn.vote.domain.Voteinfo;
import cn.vote.domain.Voter;
import cn.vote.domain.Voterresult;
import cn.vote.service.LoginService;
import cn.vote.service.VoteinfoService;
import cn.vote.uitls.CTool;
import cn.vote.uitls.JsonResult;
import cn.vote.uitls.JsonResultType;

public class VoteinfoServlet extends BaseServlet {
	private VoteinfoService voteinfoService = new VoteinfoService();
	//密码解码
	private String decodePassword(String epassword) {
		String[] arr = epassword.split("-");
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < arr.length; i++) {
			String code = Integer.toHexString(Integer.parseInt(arr[i],8));
			sb.append("\\u");
			sb.append(code);
		}
		return CTool.decodeUnicode(sb.toString()).toString();
	}
	/**
	 * 获取voter投票结果
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String voteResult(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Voter voter = (Voter)req.getSession().getAttribute("sessionUser");
		
		String[] group1values = req.getParameterValues("group1");
		String[] group2values = req.getParameterValues("group2");
		String[] group3values = req.getParameterValues("group3");
		
		List<Voterresult> oneList = new ArrayList<Voterresult>();
		List<Voterresult> twoList = new ArrayList<Voterresult>();
		List<Voterresult> threeList = new ArrayList<Voterresult>();
		
		List list1 = (List) req.getSession().getAttribute("voteinfoList1");
		List list2 = (List) req.getSession().getAttribute("voteinfoList2");
		List list3 = (List) req.getSession().getAttribute("voteinfoList3");
		
		//类别为“1”的;
		if (group1values != null && group1values.length==2) {
			for (int i = 0; i < group1values.length; i++) {
				/*
				 *1、先判断用户是否投过票
				 *2、如果没有，就投；有的话，就拒绝，保存信息返回vote.jsp页面 
				 */
				Voterresult judge = voteinfoService.judge(voter.getUsername());
				if (judge == null) {
					voteinfoService.insert(group1values[i],voter.getUsername(),1);//worksid，voter，类别category
				}else {
					req.setAttribute("error1", "您已经选过了！");
				}
			}
		}else {
			req.setAttribute("error2", "只能选两个，请勿多选或者少选");
		}
		req.getSession().setAttribute("oneList", oneList);
		
		//类别为“2”的;
		
		if (group2values != null && group2values.length==2) {
			for (int i = 0; i < group2values.length; i++) {
				Voterresult judge = voteinfoService.judge(voter.getUsername());
				if (judge == null) {
					voteinfoService.insert(group1values[2],voter.getUsername(),2);//worksid，voter，类别category
				}else {
					req.setAttribute("error1", "您已经选过了！");
				}
			 }
		}else {
			 req.setAttribute("error2", "只能选两个，请勿多选或者少选");
		}
		req.getSession().setAttribute("twoList", twoList);	
		
		//类别为“3”的;
		
			if (group3values != null && group3values.length==2) {
			for (int i = 0; i < group3values.length; i++) {
				Voterresult judge = voteinfoService.judge(voter.getUsername());
				if (judge == null) {
					voteinfoService.insert(group3values[i],voter.getUsername(),3);//worksid，voter，类别category
				}else {
					req.setAttribute("error1", "您已经选过了！");
				}
			  }
			}else {
				req.setAttribute("error2", "只能选两个，请勿多选或者少选");
		}
		req.getSession().setAttribute("threeList", threeList);	

		
		for (int i = 0; i < list1.size(); i++) {
			int w = ((Voteinfo)list1.get(i)).getWorksid();
			String worksid = Integer.toString(w);
			Voterresult voterresult = voteinfoService.getInfo(worksid, 1);
			int poll = voteinfoService.getPoll(worksid, 1);
			String percent = voteinfoService.getPercent(worksid, 1);
			Voteinfo voteinfo = voteinfoService.getWorks(worksid, 1);
			voterresult.setPoll(poll);
			voterresult.setPercent(percent);
			voterresult.setWorks(voteinfo.getWorks());
			oneList.add(voterresult);	
		}
		
		for (int i = 0; i < list2.size(); i++) {
			int w = ((Voteinfo)list2.get(i)).getWorksid();
			String worksid = Integer.toString(w);
			System.err.println("worksid:"+worksid);
			Voterresult voterresult = voteinfoService.getInfo(worksid, 2);
			System.err.println("voterresult"+voterresult);
			int poll = voteinfoService.getPoll(worksid, 2);
			System.err.println("poll:"+poll);
			String percent = voteinfoService.getPercent(worksid, 2);
			Voteinfo voteinfo = voteinfoService.getWorks(worksid, 2);
			voterresult.setPoll(poll);
			voterresult.setPercent(percent);
			voterresult.setWorks(voteinfo.getWorks());
			twoList.add(voterresult);	
		}
		for (int i = 0; i < list3.size(); i++) {
			int w = ((Voteinfo)list3.get(i)).getWorksid();
			String worksid = Integer.toString(w);
			Voterresult voterresult = voteinfoService.getInfo(worksid, 3);
			int poll = voteinfoService.getPoll(worksid, 3);
			String percent = voteinfoService.getPercent(worksid, 3);
			Voteinfo voteinfo = voteinfoService.getWorks(worksid, 3);
			voterresult.setPoll(poll);
			voterresult.setPercent(percent);
			voterresult.setWorks(voteinfo.getWorks());
			threeList.add(voterresult);	
		}
		req.getSession().setAttribute("sessionVoter", "已经投好了！");
		
		System.err.println("onelist"+oneList);
		System.err.println("twolist"+twoList);
		System.err.println("threelist"+threeList);
		
		return "f:/jsps/vote.jsp";
	}
	
	/**
	 * 初始化页面
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String init(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<Voteinfo> voteinfoList1 = voteinfoService.getWorksInfo(1);//得到类别为“1”的作品信息
		System.err.println("init:" + voteinfoList1);
		req.getSession().setAttribute("voteinfoList1", voteinfoList1);
		List<Voteinfo> voteinfoList2 = voteinfoService.getWorksInfo(2);//得到类别为“2”的作品信息
		req.getSession().setAttribute("voteinfoList2", voteinfoList2);
		List<Voteinfo> voteinfoList3 = voteinfoService.getWorksInfo(3);//得到类别为“3”的作品信息
		req.getSession().setAttribute("voteinfoList3", voteinfoList3);
		return "f:/jsps/vote.jsp";
	}

	/**
	 * 登录
	 */
	public void login(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			//设置响应内容为json格式
			resp.setContentType("text/json;charset=utf-8");
			
		
			System.err.println("调用");
			 Map<String, Cookie> cookieMap = getCookieMap(req);

				String username = req.getParameter("username");	
				String epassword = req.getParameter("password");
				String password = decodePassword(epassword);
				String token = (String) req.getSession().getAttribute("token");
				String timeStamp = req.getParameter("timeStamp");
				String salt = req.getParameter("salt");
				//var salt = $.md5(username+password+timeStamp+token);
				String rightSalt = CTool.MD5(username+password+timeStamp+token);	
				
				if (!rightSalt.equals(salt)) {//进行校验
					JsonResult jsonResult = new JsonResult(JsonResultType.IllegalOperation, "非法操作");
					String json = JSONObject.fromObject(jsonResult).toString();
					resp.getWriter().print(json);
					return;
				}
				//调用service方法
				JsonResult jsonResult = LoginService.login(username, password);
				
				
//				if (req.getSession().getAttribute("sessionUser")!=null) {
//					Object object = req.getSession().getAttribute("sessionUser");
//					Voter v = (Voter)object;
//					
//					if (cookieMap.get("username").getValue()==v.getUsername()&& cookieMap.get("password").getValue()==v.getPassword() ) {					
//						jsonResult.setAppendData(req.getContextPath()+"/vote.jsp");
//						String json = JSONObject.fromObject(jsonResult).toString();
//						System.err.println(json);
//						resp.getWriter().print(json);
//					}
//				
//				}else {
				if (jsonResult.getResultType() == JsonResultType.Success) {
					
					//保存用户到session
					req.getSession().setAttribute("sessionUser", jsonResult.getAppendData());
					System.err.println("session" + req.getSession().getAttribute("sessionUser"));
					//设置cookie
					Cookie cookie = new Cookie("username", username);
					cookie.setMaxAge(60 * 60 * 24 * 10);//保存十天
					resp.addCookie(cookie);
					Cookie cookie2 = new Cookie("password", password);
					cookie2.setMaxAge(60*60*24*10);//保存十天
					resp.addCookie(cookie2);
					//重定向的url
					jsonResult.setAppendData(req.getContextPath()+"/jsps/vote.jsp");
					String json = JSONObject.fromObject(jsonResult).toString();
					System.err.println(json);
					resp.getWriter().print(json);
					return;
				}
			return;
		//}
	}
	/**
	 * 得到cookie集合
	 * @param req
	 * @return
	 */
	private Map<String, Cookie> getCookieMap(HttpServletRequest req){
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		 //获取浏览器访问访问服务器时传递过来的cookie数组
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;		
	}
}
